package parkingManage.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import parkingManage.dao.CarDao;
import parkingManage.model.CarModel;
import parkingManage.utils.DBUtils;

public class CarDaoImpl implements CarDao {

	@Override
	public List<CarModel> selectAllCar() {
		List<CarModel> list = new ArrayList<CarModel>();

		Connection conn = DBUtils.getConnection();
		Statement sta = null;
		ResultSet rs = null;

		try {
			// 获取状态集
			sta = conn.createStatement();

			// 执行sql语句
			String sql = "select * from car";
			rs = sta.executeQuery(sql);

			while (rs.next()) {
				String license = rs.getString("license");
				int height = rs.getInt("height");

				CarModel car = new CarModel(license, height);
				list.add(car);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接
			DBUtils.closeAll(sta, conn, rs);
		}
		return list;
	}

	@Override
	public CarModel selectByLicense(String license) {
		Connection conn = null;
		conn = DBUtils.getConnection();

		CarModel car = null;
		ResultSet rs = null;
		PreparedStatement ps = null;

		try {
			String sql = "select * from car where license = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, license);

			rs = ps.executeQuery();

			while(rs.next()) {
				int height = rs.getInt("height");
				car = new CarModel(license, height);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(ps, conn, rs);
		}
		return car;
	}

	@Override
	public int saveCar(CarModel cars) {
		Connection conn = null;
		conn = DBUtils.getConnection();

		PreparedStatement ps = null;
		int num = 0;

		try {
			String sql = "insert into car(license,height) values(?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, cars.getLicense());
			ps.setInt(2, cars.getHeight());

			num = ps.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtils.closeAll(ps, conn, null);
		}
		return num;
	}

}
